BASE:=$(shell pwd | xargs basename)
CPPFLAGS = -I. -I ../../3rd/antlr/include -I ../../3rd/libantlr3c-3.2 -I ../../include
CPPSOURCES=${wildcard *.cpp}
CSOURCES=${wildcard *.c}
GSOURCES=${wildcard *.g}
VERSION=?-g


EXTENSION=
ifeq ($(VERSION),-g)
EXTENSION=-g
endif

ANTLR_LEX_SOURCES=$(patsubst %.g,%Lexer.c, $(GSOURCES))
ANTLR_PRS_SOURCES=$(patsubst %.g,%Parser.c, $(GSOURCES))
ANTLR_LEX_CPPSOURCES=$(patsubst %.g,%Lexer.cpp, $(GSOURCES))
ANTLR_PRS_CPPSOURCES=$(patsubst %.g,%Parser.cpp, $(GSOURCES))
ANTLR_PRS_HEADERS =$(patsubst %.g,%Parser.h, $(GSOURCES))
ANTLR_LEX_HEADERS =$(patsubst %.g,%Lexer.h, $(GSOURCES))
ANTLR_CSOURCES=$(ANTLR_LEX_SOURCES) $(ANTLR_PRS_SOURCES)
ANTLR_LEX_OBJECT=$(patsubst %.cpp,%$(EXTENSION).o, $(ANTLR_LEX_CPPSOURCES))
ANTLR_PRS_OBJECT=$(patsubst %.cpp,%$(EXTENSION).o, $(ANTLR_PRS_CPPSOURCES))
ANTLR_CPPSOURCES=$(ANTLR_LEX_CPPSOURCES) $(ANTLR_PRS_CPPSOURCES)
ANTLR_HEADERS=$(ANTLR_LEX_HEADERS) $(ANTLR_PRS_HEADERS)
OBJECTS=$(patsubst %.cpp,%$(EXTENSION).o, $(ANTLR_CPPSOURCES))


ifneq ($(findstring clean,$(MAKECMDGOALS)),clean)
-include $(SOURCE_DEPENDENCIES)
endif
 

../../lib/lib$(BASE)$(EXTENSION).a: $(OBJECTS)
	ar rcs $@ $(OBJECTS)
	for i in $(OBJECTS); do \
		rm $$i;\
	done

$(OBJECTS):$(ANTLR_CPPSOURCES)
	ag++ -c $(CPPFLAGS) $(ANTLR_LEX_CPPSOURCES) -o $(ANTLR_LEX_OBJECT)
	ag++ -c $(CPPFLAGS) $(ANTLR_PRS_CPPSOURCES) -o $(ANTLR_PRS_OBJECT)
	for i in $(OBJECTS); do \
		cp $$i ../../.objs;\
	done

%.cpp: %.c
	mv $< $@

$(ANTLR_CSOURCES) $(ANTLR_HEADERS): $(GSOURCES)
	java -jar ../../3rd/antlr-3.2.jar $(GSOURCES)
	@echo $(ANTLR_PRS_HEADERS)
	@echo $(ANTLR_LEX_HEADERS)
	cp $(ANTLR_PRS_HEADERS) ../../include/$(ANTLR_PRS_HEADERS)
	cp $(ANTLR_LEX_HEADERS) ../../include/$(ANTLR_LEX_HEADERS)
echo:
	@echo $(BASE)
	@echo $(GSOURCES)
	@echo $(OBJECTS)
	@echo $(ANTLR_CSOURCES)
	@echo $(ANTLR_HEADERS)
	#@echo $(SOURCE_DEPENDENCIES)

clean:
	rm -f *.o *.h *.cpp *.c *.d *.tokens ../../include/$(ANTLR_PRS_HEADERS) ../../include/$(ANTLR_LEX_HEADERS)

